package com.feicheng.iou.controller.image;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.feicheng.iou.exception.SystemExceptionV110;
import com.feicheng.iou.result.ResultInfoV110;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.iterators.LazyIteratorChain;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author tianchunlei
 * @Des //图片上传接口
 * @Date 2021/8/10
 **/
@RestController
@RequestMapping("/iou/image")
@Slf4j
@CrossOrigin
public class ImageUploadController {

    @Value("${image.student.idcard}")
    private String idcardFilePath;

    @Value("${image.resource.record}")
    private String recordFilePath;

    @RequestMapping("/upload")
    public Map<String,String> upload(MultipartFile idcardImg,String type) {
        log.info("ImageUploadController的upload方法进入,type= " + type);
        //定义要保存的文件目录变量
        String filePath = "";
        //获取图片的名字包含扩展名
        String imgName = IdUtil.simpleUUID() + idcardImg.getOriginalFilename();
        Map<String,String> map = new HashMap<>();
        if ("idcard".equals(type)) {
            //如果上传时携带的type为idcard代表是身份证，那么统一存储在idcardFilePath目录下
            filePath = idcardFilePath;
        }
        if ("record".equals(type)) {
          //如果上传时携带的type为record，统一保存在recordFilePath目录下
            filePath = recordFilePath;
        }
        //创建文件目录
        File file = new File(filePath);
        //构建全路径   文件路径+文件名
        String path = "";
        try {
            //如果文件目录不存在创建目录
            if (!file.exists()) {
                file.mkdirs();
            }
            //构建全路径
            path = filePath + "/" + imgName;

            log.info("文件保存全路径为: " + path);

            File fileAll = new File(path);
            fileAll.createNewFile();
            //保存操作
            idcardImg.transferTo(fileAll);
            map.put("STATUS","SUCCESS");
            map.put("URL",imgName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }
}
